<template>
  <view class="consignment-page">
    <!-- 底部分享按钮 -->
    <button class="float-share-btn" open-type="share">
      <text class="share-text">分享</text>
    </button>
    
    <!-- 寄售清单 -->
    <scroll-view 
      class="item-list" 
      scroll-y 
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      refresher-threshold="50"
      refresher-default-style="black"
      lower-threshold="400"
      scroll-with-animation
    >
      <view class="item" v-for="item in displayItems" :key="item.id" @click="navigateToDetail(item)">
        <!-- 商品图片 -->
        <image :src="item.imageUrl" class="item-image"></image>
        
        <!-- 商品信息 -->
        <view class="item-info">
          <text class="item-name">{{ item.name }}</text>
          <text class="item-price">¥{{ item.price }}</text>
          <text class="item-description">{{ item.description }}</text>
        </view>
        
        <!-- 联系电话图标 -->
        <view class="phone-icon" @click.stop="makePhoneCall(item.contactTel || merchantContact.phone)">
          <text class="iconfont icon-phone"></text>
        </view>
      </view>
      
      <!-- 加载状态提示 -->
      <view class="loading-more" v-if="isLoading">
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 无更多数据提示 -->
      <view class="no-more" v-if="!hasMore && !isLoading && currentPage > 1">
        <text class="no-more-text">— 没有更多数据了 —</text>
      </view>
    </scroll-view>

    <!-- 商家联系方式弹窗 -->
    <view class="modal" v-if="selectedItem">
      <view class="modal-content">
        <text class="modal-title">商家联系方式</text>
        <text>电话: {{ merchantContact.phone }}</text>
        <text>微信: {{ merchantContact.wechat }}</text>
        <view class="modal-buttons">
          <button class="call-button" @click="makePhoneCall(merchantContact.phone)">一键拨打</button>
          <button class="close-button" @click="closeModal">关闭</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getConsignmentList } from '@/api/getApiResult.js';

// --- 分页数据 ---
const pageSize = 5; // 每页显示数量
const currentPage = ref(1);
const hasMore = ref(true);
const isLoading = ref(false);
const isRefreshing = ref(false);

// 生成随机价格
const getRandomPrice = () => {
  return Math.floor(Math.random() * 10000) + 500;
};

// 生成随机描述
const getRandomDescription = () => {
  const conditions = ['全新未拆封', '9成新', '8成新', '95%新', '包装完好'];
  const features = ['限量版', '珍藏版', '收藏版', '纪念版', '原厂包装'];
  const extras = ['带包装盒', '带防伪标签', '带收藏证书', '原厂配件齐全', '私人酒窖存放'];
  
  return `${conditions[Math.floor(Math.random() * conditions.length)]}, ${features[Math.floor(Math.random() * features.length)]}, ${extras[Math.floor(Math.random() * extras.length)]}`;
};

// 生成大量假数据
const generateFakeItems = (count) => {
  const wines = [
    '茅台', '五粮液', '剑南春', '国窖1573', '洋河蓝色经典', '泸州老窖', '汾酒', '郎酒', 
    '拉菲', '拉图', '玛歌', '木桐', '侯伯王', '罗曼尼康帝', '柏图斯', '奔富', '奔富BIN128',
    '轩尼诗XO', '人头马XO', '马爹利XO', '芝华士', '杰克丹尼', '尊尼获加', '百龄坛', '格兰菲迪'
  ];
  
  const years = ['2010年', '2012年', '2015年', '2018年', '2020年', '82年', '90年', '95年', '陈年'];
  const types = ['珍藏', '典藏', '特酿', '窖藏', '限量', '特级', '顶级', '尊享'];
  
  const items = [];
  for (let i = 1; i <= count; i++) {
    const wine = wines[Math.floor(Math.random() * wines.length)];
    const year = years[Math.floor(Math.random() * years.length)];
    const type = types[Math.floor(Math.random() * types.length)];
    
    items.push({
      id: i,
      name: `${year}${wine}${type}`,
      description: getRandomDescription(),
      imageUrl: `https://via.placeholder.com/150?text=${encodeURIComponent(wine)}`,
      price: getRandomPrice()
    });
  }
  
  return items;
};

// 所有商品数据（模拟后端数据）
const allItems = generateFakeItems(30);

// 当前显示的商品数据
const items = ref([]);

// 计算属性：当前显示的商品
const displayItems = computed(() => {
  return items.value;
});

// 初始加载数据
onMounted(() => {
  loadConsignmentData();
});

// 加载个人寄售数据
const loadConsignmentData = async () => {
  try {
    const response = await getConsignmentList();
    console.log('个人寄售接口返回数据:', response);
    
    // 获取寄售数据 - 支持多种数据格式
    let consignments = [];
    
    // 如果返回的是标准格式 {code: 0, data: [...]}
    if (response && (response.code === 0 || response.code === 200) && response.data) {
      consignments = response.data;
    }
    // 如果直接返回数组
    else if (Array.isArray(response)) {
      consignments = response;
    }
    
    // 处理寄售数据
    if (consignments && consignments.length > 0) {
      items.value = consignments.map(item => ({
        id: item.id || '',
        name: item.name || '',
        description: item.description || '',
        price: item.price || 0,
        imageUrl: (item.image && Array.isArray(item.image) && item.image.length > 0) ? item.image[0] : 'https://picsum.photos/150/150?random=' + Math.random(),
        contactTel: item.contactTel || ''
      }));
      
      console.log('个人寄售数据已加载，数量:', items.value.length);
      
      // 判断是否还有更多数据（这里假设接口返回的是全部数据）
      hasMore.value = false;
    } else {
      console.log('暂无个人寄售数据');
      items.value = [];
      hasMore.value = false;
    }
  } catch (error) {
    console.error('加载个人寄售数据失败:', error);
    // 使用默认数据作为备选
    loadDefaultData();
  }
};

// 加载默认数据（API失败时使用）
const loadDefaultData = () => {
  const initialItems = allItems.slice(0, pageSize);
  items.value = initialItems;
  hasMore.value = allItems.length > pageSize;
};

// 若首屏不够滚动，自动预加载更多数据
const ensureScrollableData = async () => {
  // 最多预加载到 3 页（避免一次性加载过多）
  while (hasMore.value && items.value.length < pageSize * 3) {
    await loadMore();
    await new Promise(resolve => setTimeout(resolve, 50));
  }
};

// 加载更多数据（由于接口返回全部数据，这里不再加载更多）
const loadMore = async () => {
  if (!hasMore.value || isLoading.value) return;
  
  isLoading.value = true;
  console.log('加载更多数据...');
  
  // 显示加载提示
  uni.showLoading({
    title: '加载中...',
    mask: false
  });
  
  try {
    // 模拟网络请求延迟
    await new Promise(resolve => setTimeout(resolve, 300));
    
    // 由于接口返回的是全部数据，这里显示没有更多数据
    hasMore.value = false;
    uni.showToast({
      title: '没有更多数据',
      icon: 'none',
      duration: 1000
    });
  } catch (error) {
    console.error('加载数据出错:', error);
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none',
      duration: 1500
    });
  } finally {
    isLoading.value = false;
    uni.hideLoading();
  }
};

// 下拉刷新
const onRefresh = async () => {
  isRefreshing.value = true;
  console.log('下拉刷新...');
  
  try {
    // 重新调用接口获取最新数据
    await loadConsignmentData();
    console.log('刷新完成，已加载新数据');
    
    // 刷新成功提示
    uni.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 800
    });
  } catch (error) {
    console.error('刷新数据出错:', error);
    uni.showToast({
      title: '刷新失败，请重试',
      icon: 'none',
      duration: 1500
    });
  } finally {
    isRefreshing.value = false;
  }
};

// 商家联系方式（使用寄售数据中的联系电话）
const merchantContact = computed(() => {
  return {
    phone: items.value.length > 0 ? items.value[0].contactTel : '13888888888',
    wechat: 'wechat123'
  };
});

const selectedItem = ref(null);

// --- 方法 ---
const showContactModal = (item) => {
  selectedItem.value = item;
};

const closeModal = () => {
  selectedItem.value = null;
};

const makePhoneCall = (phoneNumber) => {
  uni.makePhoneCall({
    phoneNumber: phoneNumber,
  });
};

// 分享功能 - 定义页面的分享信息（小程序专用）
const onShareAppMessage = () => {
  return {
    title: '酒类寄售平台 - 优质酒类交易',
    path: '/pages/consignment/index',
    imageUrl: '/static/logo.png',
    success: () => {
      uni.showToast({
        title: '分享成功',
        icon: 'success',
        duration: 2000
      });
    },
    fail: () => {
      uni.showToast({
        title: '分享失败',
        icon: 'none',
        duration: 2000
      });
    }
  };
};

// 跳转到详情页
const navigateToDetail = (item) => {
  try {
    uni.navigateTo({
      url: '/pages/consignment/detail?id=' + encodeURIComponent(item.id),
    });
  } catch (error) {
    console.error('跳转异常:', error);
  }
};

</script>

<style scoped>
.consignment-page {
  padding: 20rpx;
  background-color: #f8f8f8;
}

/* 物品列表 */
.item-list .item {
  display: flex;
  margin-bottom: 20rpx;
  background-color: #fff;
  padding: 24rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: relative;
  align-items: center;
}

.item-image {
  width: 140rpx;
  height: 140rpx;
  border-radius: 8rpx;
  object-fit: cover;
  flex-shrink: 0;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-left: 24rpx;
  overflow: hidden;
}

.item-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 12rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-price {
  font-size: 32rpx;
  color: #ff4d4f;
  font-weight: bold;
  margin-bottom: 12rpx;
}

.item-description {
  font-size: 24rpx;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 电话图标 */
.phone-icon {
  width: 60rpx;
  height: 60rpx;
  background-color: #f8f8f8;
  border: 1px solid #e8e8e8;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 20rpx;
  flex-shrink: 0;
  transition: all 0.3s;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.phone-icon:active {
  background-color: #f0f0f0;
}

.phone-icon .iconfont {
  color: #ff4d4f;
  font-size: 32rpx;
}

/* 使用自定义图标代替 iconfont */
.icon-phone:before {
  content: "📞";
}

/* 弹窗 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.modal-content {
  background-color: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 80%;
  max-width: 600rpx;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  color: #333;
}

.modal-content text {
  margin-bottom: 20rpx;
  font-size: 28rpx;
  color: #666;
}

.modal-buttons {
  display: flex;
  width: 100%;
  justify-content: space-between;
  margin-top: 30rpx;
}

.call-button, .close-button {
  flex: 1;
  margin: 0 10rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.call-button {
  background-color: #1890ff;
  color: white;
}

.close-button {
  background-color: #f5f5f5;
  color: #666;
}

/* 加载状态提示 */
.loading-more, .no-more {
  display: flex;
  justify-content: center;
  padding: 30rpx 0;
}

.loading-text, .no-more-text {
  font-size: 24rpx;
  color: #999;
}

/* 滚动区域样式 */
.item-list {
  height: 100vh;
}

/* 分享按钮样式 */
.float-share-btn {
  position: fixed;
  bottom: 100rpx;
  right: 40rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #FFA500;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
  z-index: 999;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3);
  border: none;
}

.float-share-btn::after {
  border: none;
}

.share-text {
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
}
</style>